﻿using System;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Linq;
using HiStaff.Control;
using HiStaff.Domain.Sys;
using System.Reflection;
using System.Drawing;
using HiStaff.iSystem;
namespace HiStaff.UI
{
    public partial class Main : Form
    {
        private static string imgPath = AppDomain.CurrentDomain.BaseDirectory + "\\Images\\";
        private static readonly Random random = new Random();
        private const string RELOGIN = "RELOGIN";
        private const string COLOR_BLUE = "COLOR_BLUE";
        private const string COLOR_SILVER = "COLOR_SILVER";
        private const string COLOR_BLACK = "COLOR_BLACK";

        public Main()
        {
            this.Font = SystemFont.FontSegoeUi;
            InitializeComponent();
        }
        private void Main_Load(object sender, EventArgs e)
        {
            try
            {
                UserLogin();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Close();
            }
        }
        private void UserLogin()
        {
            this.Hide();
            Login login = new Login();
            login.ShowDialog();
            if (login.LoginResult == System.Windows.Forms.DialogResult.OK)
            {
                LoadInit loadInit = new LoadInit();
                loadInit.LoadData();
                loadInit.ShowDialog();

                if (loadInit.InitResult == System.Windows.Forms.DialogResult.OK)
                {
                    loadInit.Close();
                    login.Close();
                    SetFunction();
                    this.Show();
                }
                else
                {
                    this.Close();
                }
            }
            else
            {
                this.Close();
            }
        }
        private void ribMain_CommandClick(object sender, Janus.Windows.Ribbon.CommandEventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                switch (e.Command.Key)
                {
                    case RELOGIN:
                        foreach (var frmChild in this.MdiChildren)
                        {
                            frmChild.Close();
                        }
                        UserLogin();
                        break;
                    case COLOR_BLUE:
                        Janus.Windows.Common.VisualStyleManager.DefaultOfficeColorScheme = Janus.Windows.Common.OfficeColorScheme.Blue;
                        UnCheckColorCommand(e.Command.Key);
                        break;
                    case COLOR_SILVER:
                        Janus.Windows.Common.VisualStyleManager.DefaultOfficeColorScheme = Janus.Windows.Common.OfficeColorScheme.Silver;
                        UnCheckColorCommand(e.Command.Key);
                        break;
                    case COLOR_BLACK:
                        Janus.Windows.Common.VisualStyleManager.DefaultOfficeColorScheme = Janus.Windows.Common.OfficeColorScheme.Black;
                        UnCheckColorCommand(e.Command.Key);
                        break;
                    default:
                        OpenFormByName(e.Command.Tag.ToString(), e.Command.Key);
                        break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
        private bool OpenFormByName(string nameSpace, string formName)
        {
            Assembly assembly = Assembly.LoadFile(string.Format("{0}\\{1}.dll", AppDomain.CurrentDomain.BaseDirectory, nameSpace));
            Type form = assembly.GetType(string.Format("{0}.{1}", nameSpace, formName));

            if (form != null && (form.BaseType.Name == "Form" || 
                form.BaseType.BaseType.Name == "Form" || 
                form.BaseType.BaseType.BaseType.Name == "Form" ||
                form.BaseType.BaseType.BaseType.BaseType.Name == "Form" ||
                form.BaseType.BaseType.BaseType.BaseType.BaseType.Name == "Form"))
            {
                foreach (var frmChild in this.MdiChildren)
                {
                    if (frmChild.GetType() == form)
                    {
                        frmChild.Activate();
                        return true;
                    }
                }

                // Get the default constructor
                ConstructorInfo ci = form.GetConstructor(System.Type.EmptyTypes);

                // Call the default constructor
                Form f = ci.Invoke(null) as Form;
                if (this != null)
                {
                    f.MdiParent = this;
                    f.Show();
                }
                else
                {
                    f.ShowDialog();
                }
                return true;
            }
            else
            {
                MessageBox.Show("Không tồn tại chức năng [" + formName + "] trong hệ thống. \nVui lòng kiểm tra lại.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }
        private void SetFunction()
        {
            List<SY_FUNCTION> lstFunc = Service.SystemClient.GetFunction(new SY_FUNCTION());
            List<SY_MODULE> lstModule = Service.SystemClient.GetModule(new SY_MODULE());
            if (lstFunc.Count > 0)
            {
                // add data list
                var lstDataList = (from o in lstFunc
                                   where o.MODULEID == null
                                   select o).ToList();
                this.ribMain.BackstageCommands.Clear();
                Janus.Windows.Ribbon.ButtonCommand btnCmd;
                Janus.Windows.Ribbon.RibbonTab ribTab;
                Janus.Windows.Ribbon.RibbonGroup ribGroup;
                foreach (var item in lstDataList)
                {
                    btnCmd = new Janus.Windows.Ribbon.ButtonCommand(item.NAME, item.DESCRIPTION);
                    btnCmd.Tag = item.NAMESPACE;
                    if (!string.IsNullOrEmpty(item.IMGNAME) && System.IO.File.Exists(imgPath + item.IMGNAME))
                    {
                        btnCmd.Image = System.Drawing.Image.FromFile(imgPath + item.IMGNAME);
                    }
                    this.ribMain.BackstageCommands.Add(btnCmd);
                }
                // add ReLogin
                btnCmd = new Janus.Windows.Ribbon.ButtonCommand(RELOGIN, "Đăng nhập lại");
                if (System.IO.File.Exists(imgPath + "login.png"))
                {
                    btnCmd.Image = System.Drawing.Image.FromFile(imgPath + "login.png");
                }
                this.ribMain.BackstageCommands.Add(btnCmd);
                // add color btn
                this.ribMain.QuickAccessCommands.Clear();
                this.ribMain.QuickAccessCommands.Add(CreateBuiltInVisualStyleCommand(COLOR_BLUE, "Blue", Color.FromArgb(207, 221, 238)));
                this.ribMain.QuickAccessCommands.Add(CreateBuiltInVisualStyleCommand(COLOR_SILVER, "Silver", Color.Silver));
                this.ribMain.QuickAccessCommands.Add(CreateBuiltInVisualStyleCommand(COLOR_BLACK, "Black", Color.Black));
                // add tab module
                this.ribMain.Tabs.Clear();
                foreach (var m in lstModule)
                {
                    ribTab = new Janus.Windows.Ribbon.RibbonTab(m.NAME);
                    ribTab.Key = m.ID;
                    // add one group to tab
                    ribGroup = new Janus.Windows.Ribbon.RibbonGroup();
                    ribTab.Groups.Add(ribGroup);
                    // add function to group in tab module
                    var lstFn = (from o in lstFunc
                                 where o.MODULEID != null && o.MODULEID == m.ID
                                 select o).ToList();
                    foreach (var f in lstFn)
                    {
                        btnCmd = new Janus.Windows.Ribbon.ButtonCommand(f.NAME, f.DESCRIPTION);
                        btnCmd.Tag = f.NAMESPACE;
                        if (!string.IsNullOrEmpty(f.IMGNAME))
                        {
                            btnCmd.Image = System.Drawing.Image.FromFile(imgPath + f.IMGNAME);
                        }
                        else
                        {
                            btnCmd.Image = CreateColorImage(RandomColor(), 16, 16);
                            btnCmd.LargeImage = CreateColorImage(RandomColor(), 32, 32);
                        }

                        if (f.TYPE == 1)
                        {
                            btnCmd.SizeStyle = Janus.Windows.Ribbon.CommandSizeStyle.Large;
                        }
                        else
                        {
                            btnCmd.SizeStyle = Janus.Windows.Ribbon.CommandSizeStyle.Small;
                        }
                        ribGroup.Commands.Add(btnCmd);
                    }
                    this.ribMain.Tabs.Add(ribTab);
                }
            }
            else
            {
                MessageBox.Show("Bạn chưa được phân quyền vào hệ thống.\n Vui lòng liên hệ quản trị hệ thống.", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Close();
            }
        }
        private Color RandomColor()
        {
            return Color.FromArgb(random.Next(0, 255), random.Next(0, 255), random.Next(0, 255));
        }
        private Image CreateColorImage(Color clr, int width, int height)
        {
            Bitmap bmp = new Bitmap(width, height);
            Graphics g = Graphics.FromImage(bmp);
            g.Clear(clr);
            Rectangle r = new Rectangle(0, 0, width - 1, height - 1);
            g.DrawRectangle(Pens.Transparent, r);
            r.Inflate(-1, -1);
            g.DrawRectangle(Pens.Transparent, r);
            g.Dispose();
            return bmp;
        }
        private Janus.Windows.Ribbon.ButtonCommand CreateBuiltInVisualStyleCommand(string key, string text, Color imageColor)
        {
            Janus.Windows.Ribbon.ButtonCommand command = new Janus.Windows.Ribbon.ButtonCommand(key);
            command.SizeStyle = Janus.Windows.Ribbon.CommandSizeStyle.Small;
            command.ActAsOptionButton = true;
            command.CheckOnClick = true;
            command.Text = text;
            command.Image = CreateColorImage(imageColor, 16, 16);
            command.LargeImage = CreateColorImage(imageColor, 32, 32);

            return command;
        }
        private void UnCheckColorCommand(string keyChecked)
        {
            foreach (Janus.Windows.Ribbon.ButtonCommand btn in this.ribMain.QuickAccessCommands)
            {
                btn.Checked = btn.Key == keyChecked;
            }
        }
    }
}